from selenium import webdriver
from selenium.webdriver import ActionChains
import base64
import json
import requests

dirver_path = r"C:\Users\gmbjzg\Desktop\chromedriver_win32\chromedriver.exe"

driver = webdriver.Chrome(executable_path=dirver_path)

driver.get("http://jw.zhku.edu.cn/home.aspx")

# 切换到iframe标签
driver.switch_to.frame("frm_login")

# 1.元素获取
xhInputTag = driver.find_element_by_id("txt_asmcdefsddsd")
pwdInputTag = driver.find_element_by_id("txt_psasas")
yzmInputTag = driver.find_element_by_id("txt_sdertfgsadscxcadsads")
imgCodeTag = driver.find_element_by_id("imgCode")
submitTag = driver.find_element_by_name("btn_login")


# 5.表单填值
actions = ActionChains(driver)
actions.move_to_element(xhInputTag)
actions.send_keys_to_element(xhInputTag, "201720814306")
actions.move_to_element(pwdInputTag)
actions.send_keys_to_element(pwdInputTag, "a8301863")
actions.move_to_element(yzmInputTag)
yzmInputTag.click()

# 2.获取验证码
imgCodeTag.screenshot('yzm.jpg')


# 3.识别验证码
def base64_api(uname, pwd, img, typeid):
    with open(img, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        b64 = base64_data.decode()
    data = {"username": uname, "password": pwd, "typeid": typeid, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]
    return ""


yzmCode = base64_api('1924086038', '1924086038', 'yzm.jpg', 3)

# 4.输入验证码
actions.send_keys_to_element(yzmInputTag, yzmCode)
actions.move_to_element(submitTag)
actions.click(submitTag)

# 5.执行
actions.perform()

# 6.去除弹窗确认
driver.switch_to.alert.dismiss()
